package com.ch.android.lookforkotlinv2.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.ch.android.baselib.SpUtil
import com.ch.android.baselib.SpUtil.getSessionId
import com.ch.android.lookforkotlinv2.AppConst
import com.ch.android.lookforkotlinv2.R
import com.ch.android.lookforkotlinv2.activity.LiveActivity
import com.ch.android.lookforkotlinv2.databinding.FragmentPreviewBinding
import com.ch.android.lookforkotlinv2.vm.PreviewModel
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.video.VideoCanvas


class PreviewFragment : Fragment() {
    companion object {
        private const val REQUEST_CODE = 100
    }

    private lateinit var mBinding: FragmentPreviewBinding
    private lateinit var mResultLauncher: ActivityResultLauncher<String>
    private var mCoverUri: Uri? = null
    /**
     * Agora Rtc Engine 声网引擎
     */
    private lateinit var mRtcEngine: RtcEngine
    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 用 registerForActivityResult 替代 startActivityForResult
        // 通过 ActivityResultContracts.GetContent() 创建一个 ActivityResultLauncher 对象
        mResultLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            // Handle the returned Uri
            Log.d("PreviewFragment", "uri: $uri")
            uri?.let {
                mCoverUri = it
                mBinding.liveCover.setImageURI(mCoverUri)
            }
        }
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_preview, container, false)
        mBinding.lifecycleOwner = this
        mBinding.model = PreviewModel(requireActivity().application)
        mBinding.btnOpenLive.setOnClickListener(View.OnClickListener {
            if (mCoverUri != null) {
                mBinding.model!!.requestOpenLive(mCoverUri!!, 101, "直播标题", SpUtil.getSP().getSessionId())
            }
        })
        //打开相册
        mBinding.btnOpenAlbum.setOnClickListener(View.OnClickListener {
            mResultLauncher.launch("image/*")
        })
        mBinding.model!!.openLiveData.observe(viewLifecycleOwner) { openLiveData ->
            //打开直播
            LiveActivity.startActivity(requireActivity(), openLiveData)
        }
        initAndJoinChannel()
        return mBinding.root
    }

    /**
     * 初始化RtcEngine
     */
    private fun initAndJoinChannel() {
        // 设置音士频的参数
        try {
            mRtcEngine = RtcEngine.create(this.requireContext().applicationContext, AppConst.AGORA_APP_ID, mRtcEventHandler)
            // 视频默认禁用，你需要调用 enableVideo 启用视频流。
            mRtcEngine.enableVideo()
            // 开启本地视频预览。
            mRtcEngine.startPreview()
            // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象。
            val surfaceView = SurfaceView(this.context)
            mBinding.previewContainer.addView(surfaceView)
            // 将 SurfaceView 对象传入 Agora，以渲染本地视频。
            mRtcEngine.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}